<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref } from 'vue'
import { useUserStore } from '@/stores/index.js'
import { userUpdateInfoService } from '@/api/user.js'

const {
  userInfo: { username, nickname, id, email },
  getUserInfo
} = useUserStore()

const form = ref({
  id,
  username,
  nickname,
  email
})

const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}/,
      message: '长度在 2 到 10 个非空字符',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ]
}

const formRef = ref()
const isLoading = ref(false)
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 这里可以添加提交数据到服务器的逻辑
      isLoading.value = true
      await userUpdateInfoService(form.value)
      getUserInfo()
      isLoading.value = false
      ElMessage.success('个人信息修改成功！')
    } else {
      ElMessage.error('请检查输入的信息')
      return false
    }
  })
}
defineOptions({
  name: 'UserProfile'
})
</script>

<template>
  <PageContainer title="基本资料" v-loading="isLoading">
    <!-- 表单部分 -->
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-position="top"
      style="width: 500px"
    >
      <el-form-item label="登录名称" prop="username">
        <el-input v-model="form.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="form.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交修改</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>

<style scoped></style>
